package cn.hqm.hqmtechnology.controller;

import cn.hqm.hqmtechnology.annotations.PassToken;
import cn.hqm.hqmtechnology.common.R;
import cn.hqm.hqmtechnology.utils.RedisUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping
public class CaptchaController {

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/captcha")
    @PassToken
    public R generateCaptcha(HttpServletResponse response) throws IOException {
        int width = 120;
        int height = 50;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 生成随机验证码
        String captcha = generateCaptchaText(6);
        // 将验证码存储在会话或者缓存中，以便后续验证

        redisUtil.setForValueOverTime(captcha,"",5L, TimeUnit.MINUTES);

        // 绘制背景
        g.setColor(Color.PINK);
        g.fillRect(0, 0, width, height);

        // 绘制验证码文本
        g.setColor(Color.BLUE);
        g.setFont(new Font("Arial", Font.BOLD, 30));
        g.drawString(captcha, 10, 35);

        // 绘制干扰线
        g.setColor(Color.GRAY);
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();

        // 将验证码图片转换为Base64编码
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);


        // 返回Base64编码的图片
        return R.ok(base64Image);
    }

    private String generateCaptchaText(int len) {
        // 生成验证码的代码
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <len; i++) {
            sb.append(random.nextInt(10)); // 生成 1 到 10 之间的随机数
        }
        Object forValue = redisUtil.getForValue(sb.toString());
        if (Objects.nonNull(forValue)) {
            return generateCaptchaText(6);
        }
        return sb.toString();
        // ...
    }
}